package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Slf4j
@Component
public class AutoFillAspect {


    /**
     * 切点表达式
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..))&&@annotation(com.sky.annotation.AutoFill)")
    public void pt() {
    }

    @Before("pt()")
    public void autoFillAspect(JoinPoint joinPoint) {
        log.info("开始进行公共字段填充");
        //1.获取到当前被拦截方法上的数据操作类型
        //1.1获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取方法上的@AutoFill注解
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        //获取注解的值
        OperationType operationType = annotation.value();
        //获取目标方法的参数列表
        Object[] args = joinPoint.getArgs();
        //2.获取当前被拦截方法的参数---实体对象
        //2.1 获取参数
        Object entiy = args[0];

        try {
            if (operationType == OperationType.INSERT) {
                //利用反射获取get、set方法
                Method setCrateTime = entiy.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCrateUser = entiy.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateTime = entiy.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entiy.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setCrateTime.invoke(entiy, LocalDateTime.now());
                setCrateUser.invoke(entiy, BaseContext.getCurrentId());
                setUpdateTime.invoke(entiy, LocalDateTime.now());
                setUpdateUser.invoke(entiy, BaseContext.getCurrentId());
            } else if (operationType == OperationType.UPDATE) {
                Method setUpdateTime = entiy.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entiy.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateTime.invoke(entiy, LocalDateTime.now());
                setUpdateUser.invoke(entiy, BaseContext.getCurrentId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
